package com.bshinfo.web.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bshinfo.web.base.cache.RedisCacheTemplate;
import com.bshinfo.web.base.controller.BaseController;
import com.bshinfo.web.base.util.ConstantUtil;
import com.bshinfo.web.base.util.DatatableUtil;
import com.bshinfo.web.base.util.DateUtil;
import com.bshinfo.web.base.util.UUIDTool;
import com.bshinfo.web.model.UserInfo;
import com.bshinfo.web.model.dataTableUtil.DataTableModel;
import com.bshinfo.web.model.dataTableUtil.DataTableParam;
import com.bshinfo.web.service.serviceI.role.RoleServiceI;

/**
 * Role控制层 <br/>
 * 
 * 功能描述: 对Role做数据获取封装与页面控制跳转 <BR/>
 * 
 * @author 	[hezhijian]
 * 
 * @see 	[RoleController]
 * 
 * @since 	[JDK 1.7] 
 * 
 * @version [1.0]
 * 
 * @Date    [2017-2-20 10:11:09]
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController
{
	public static Logger logger = Logger.getLogger(RoleController.class);

	/**
	 * 跳转到主页面roleManage.ftl
	 * 
	 * @Param [javax.servlet.http.HttpServletRequest] request 请求对象  
	 * 
	 * @Param [javax.servlet.http.HttpServletResponse] response 响应对象
	 * 
	 * @return [String] 
	 * 
     * @author [hezhijian]
     * 
     * @Date   [2017-2-17 16:29:26]
	 */
	@RequestMapping("/toRoleManage.bsh")
	public String toRoleManage(HttpServletRequest request,HttpServletResponse response) 
	{
		return "baseData/systemManage/role/roleManage.ftl";
	}
	
	/**
	 * 获取角色数据
	 * 
	 * @Param [javax.servlet.http.HttpServletRequest] request 请求对象  
	 * 
	 * @Param [javax.servlet.http.HttpServletResponse] response 响应对象
	 * 
	 * @Param [com.bshinfo.web.model.dataTableUtil.DataTableParam[]] dataTableParams 前台传过来的数组
	 * 
	 * @return [com.bshinfo.web.model.dataTableUtil.DataTableModel] 
	 * 
     * @author [hezhijian]
     * 
     * @Date   [2017-2-17 16:29:26]
	 */
	@RequestMapping("/doGetRoleList.bsh")
	@ResponseBody
	public Object doGetRoleList(HttpServletRequest request,HttpServletResponse response, @RequestBody DataTableParam[] dataTableParams) 
	{
		Map<String, String> dataTableMap = DatatableUtil.convertToMap(dataTableParams);
		DataTableModel dataTableModel = new DataTableModel();
		
		try
		{
			dataTableModel = roleServiceI.roleList(dataTableMap);
		}
		catch(Exception e)
		{
			logger.error("[请求角色列表数据异常-ErrorMsg:]", e);
		}
		return dataTableModel;
	}
	
	/**
	 * 获取权限数据
	 * 
	 * @Param [javax.servlet.http.HttpServletRequest] request 请求对象  
	 * 
	 * @Param [javax.servlet.http.HttpServletResponse] response 响应对象
	 * 
	 * @return [net.sf.json.JSONObject] 
	 * 
     * @author [hezhijian]
     * 
     * @Date   [2017-2-17 16:29:26]
	 */
	@RequestMapping("/doGetPowerTree.bsh")
	@ResponseBody
	public JSONObject doGetPowerTree(HttpServletRequest request,HttpServletResponse response) 
	{
		List<Map<String,Object>> tree;
		
		JSONObject json = new JSONObject();
		
		try
		{
			tree = roleServiceI.getPowerTree();
			json.put("tree", tree);
			json.put("status", "success");
			json.put("msg", "请求权限树信息成功！");
		}
		catch(Exception e)
		{
			logger.error("[请求权限树异常-ErrorMsg:]", e);
			json.put("status", "error");
			json.put("msg", "请求权限树异常！");
		}
		
		return json;
	}
	
	/**
	 * 新增角色
	 * 
	 * @Param [java.lang.String[]] power 权限id的集合 
	 * 
	 * @Param [javax.servlet.http.HttpServletRequest] request 请求对象  
	 * 
	 * @Param [javax.servlet.http.HttpServletResponse] response 响应对象
	 * 
	 * @Param [javax.servlet.http.HttpSession] session 会话对象
	 * 
	 * @return [net.sf.json.JSONObject] 
	 * 
     * @author [hezhijian]
     * 
     * @Date   [2017-2-22 09:28:17]
	 */
	@RequestMapping("/doAddRole.bsh")
	@ResponseBody
	public JSONObject doAddRole(String[] power,HttpServletRequest request,HttpServletResponse response,HttpSession session) 
	{
		
		JSONObject json = new JSONObject();
		String roleId = request.getParameter("roleId");//
		String roleName = request.getParameter("roleName");
		String description = request.getParameter("description");
		String time = DateUtil.getDateString(null);
		List<String> list = new ArrayList<String>();
		for (String str : power) 
		{
			list.add(str);
		}
		
		//超管id
		UserInfo userInfo = (UserInfo) session.getAttribute("userInfo");//当前登录的用户
		String userId = userInfo.getId();//当前登录的用户Id
		
		//给权限添加上类型
		List<Map<String, Object>> powerList = roleServiceI.getPowerType(list);
						
		Map<String, Object> roleMap = new HashMap<String, Object>();
		
		roleMap.put("roleId", roleId);
		roleMap.put("roleName", roleName);
		roleMap.put("description", description);
		roleMap.put("powerList", powerList);
		roleMap.put("userId", userId);
		roleMap.put("time", time);
		
		int i = 0;
		
		try
		{
			//检测名字重复
			i = roleServiceI.checkName(roleMap);
			if(i > 0)
			{
				json.put("status", "false");
				json.put("msg", "角色名称重复，请修改！");
			}else 
			{
				if("0".equals(roleId))
				{
					String id = UUIDTool.randomUUID();
					roleMap.put("roleId", id);
					
					for(Map<String, Object> map : powerList)
					{
						map.put("roleId", id);
						map.put("userId", userId);
						map.put("time", time);
					}
					roleMap.put("powerList", powerList);
					//新增角色
					i = roleServiceI.addRole(roleMap);
					if(i > 0)
					{
						json.put("status", "success");
						json.put("msg", "角色添加成功！");
					}
				}else 
				{
					for(Map<String, Object> map : powerList)
					{
						map.put("roleId", roleId);
						map.put("userId", userId);
						map.put("time", time);
					}
					roleMap.put("powerList", powerList);
					//修改角色
					i = roleServiceI.editRole(roleMap);
					if(i > 0)
					{
						json.put("status", "success");
						json.put("msg", "角色修改成功！");
						
						//查询该角色是被那些人使用
						List<Map<String, Object>> roleList = roleServiceI.getUserIdById(roleId);
						if(roleList.size() > 0)
						{
							//存放要删除的resource
							List<String> resourceList = new ArrayList<String>();
							//存放要删除的menu
							List<String> menuList = new ArrayList<String>();
							
							for(Map<String, Object> map : roleList)
							{
								resourceList.add(map.get("user_id").toString() + "_resource");
								for(Map<String, Object> pow : powerList)
								{
									if(Integer.valueOf(pow.get("type").toString()) == 2)
									{
										menuList.add(map.get("user_id").toString() + "_menu_" + pow.get("id").toString());
									}
								}
							}
							//删除缓存中的resource
							redisCacheTemplate.del(resourceList);
							//删除缓存中的menu
							redisCacheTemplate.del(menuList);
						}
					}
				}
			}
		}
		catch(Exception e)
		{
			logger.error("[请求新增编辑角色信息异常-ErrorMsg:]", e);
			json.put("status", "error");
			json.put("msg", "请求新增编辑角色信息异常！");
		}
		
		return json;
	}
	
	/**
	 * 根据id查询角色信息
	 * 
	 * @Param [javax.servlet.http.HttpServletRequest] request 请求对象  
	 * 
	 * @Param [javax.servlet.http.HttpServletResponse] response 响应对象
	 * 
	 * @return [net.sf.json.JSONObject] 
	 * 
     * @author [hezhijian]
     * 
     * @Date   [2017-2-22 13:15:42]
	 */
	@RequestMapping("/doGetRoleById.bsh")
	@ResponseBody
	public JSONObject doGetRoleById(HttpServletRequest request,HttpServletResponse response) 
	{
		
		JSONObject json = new JSONObject();
		String roleId = request.getParameter("id");
		
		try
		{
			Map<String, Object> map = roleServiceI.selectRoleById(roleId);
			//根据角色id获得该角色所拥有的权限，并且拼成树的要求格式
			List<Map<String,Object>> tree = roleServiceI.getPowerTreeById(roleId);
			
			json.put("tree", tree);
			json.put("role", map);
			json.put("status", "success");
		}
		catch(Exception e)
		{
			logger.error("[请求角色信息异常-ErrorMsg:]", e);
			json.put("status", "error");
			json.put("msg", "请求角色信息异常！");
		}
		
		return json;
	}
	
	/**
	 * 根据id删除角色信息
	 * 
	 * @Param [javax.servlet.http.HttpServletRequest] request 请求对象  
	 * 
	 * @Param [javax.servlet.http.HttpServletResponse] response 响应对象
	 * 
	 * @return [net.sf.json.JSONObject] 
	 * 
     * @author [hezhijian]
     * 
     * @Date   [2017-2-22 15:57:12]
	 */
	@RequestMapping("/doDeleteRoleById.bsh")
	@ResponseBody
	public JSONObject doDeleteRoleById(HttpServletRequest request,HttpServletResponse response) 
	{
		
		JSONObject json = new JSONObject();
		String id = request.getParameter("id");
		
		try
		{
			//判断是否是超管
			if(ConstantUtil.ADMIN_ROLE_ID.equals(id))
			{
				json.put("userInfo", "该角色是超管，不能被删除！");
				json.put("status", "false");
			}else
			{
				//查询该角色是否被使用
				List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
				userList = roleServiceI.checkRoleById(id);
				
				if(userList.size() > 0)
				{
					String userInfo = "";
					for(Map<String, Object> map : userList)
					{
						userInfo = userInfo + " 该角色属于：" + map.get("user_name") + ",所属站点为：" +  map.get("site_name") + ". ";
					}
					json.put("userInfo", userInfo);
					json.put("status", "false");
				}else 
				{
					List<String> roleIdList = new ArrayList<String>();
					roleIdList.add(id);
					roleServiceI.deleteRoleById(roleIdList);
					
					json.put("msg", "删除成功");
					json.put("status", "success");
				}
			}
			
		}
		catch(Exception e)
		{
			logger.error("[请求删除角色异常-ErrorMsg:]", e);
			json.put("status", "error");
			json.put("msg", "请求删除角色异常！");
		}
		
		return json;
	}
	
	/**
	 * 根据ids批量删除角色信息
	 * 
	 * @Param [java.lang.String[]] roleIds 角色id的集合
	 * 
	 * @Param [javax.servlet.http.HttpServletRequest] request 请求对象  
	 * 
	 * @Param [javax.servlet.http.HttpServletResponse] response 响应对象
	 * 
	 * @return [net.sf.json.JSONObject] 
	 * 
     * @author [hezhijian]
     * 
     * @Date   [2017-2-22 17:01:42]
	 */
	@RequestMapping("/doBatchDeleteRoleById.bsh")
	@ResponseBody
	public JSONObject doBatchDeleteRoleById(String[] roleIds) 
	{
		
		JSONObject json = new JSONObject();
		List<String> roleIdList = new ArrayList<String>();
		for (String str : roleIds) 
		{
			roleIdList.add(str);
		}
		
		try
		{
			//判断是否选择了超管
			if(roleIdList.contains(ConstantUtil.ADMIN_ROLE_ID))
			{
				json.put("roleInfo", "选择中有超管，超管不能删除！请重新选择。");
				json.put("status", "false");
			}else 
			{
				//查询该角色是否被使用
				List<Map<String, Object>> roleList = new ArrayList<Map<String, Object>>();
				roleList = roleServiceI.checkRoleByIds(roleIdList);
				
				if(roleList.size() > 0)
				{
					String roleInfo = "所选的角色中，有：";
					for(Map<String, Object> map : roleList)
					{
						roleInfo = roleInfo + map.get("role_name") + "," ;
					}
					roleInfo = roleInfo.substring(0,roleInfo.lastIndexOf(",")) + "已经被使用，不能进行删除！";
					json.put("roleInfo", roleInfo);
					json.put("status", "false");
				}else 
				{
					roleServiceI.deleteRoleById(roleIdList);
					json.put("msg", "删除成功");
					json.put("status", "success");
				}
			}
			
		}
		catch(Exception e)
		{
			logger.error("[请求批量删除角色异常-ErrorMsg:]", e);
			json.put("status", "error");
			json.put("msg", "请求批量删除角色异常！");
		}
		
		return json;
	}
	
	@Resource
	private RoleServiceI roleServiceI;
	
	@Resource
	private RedisCacheTemplate redisCacheTemplate;
	
}
